//
//  FSNewSendDetailController.m
//  Trade
//
//  Created by 刘沿 on 16/4/11.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSNewSendDetailController.h"
#import "GDataDefines.h"
#import <QuickLook/QuickLook.h>

@interface FSNewSendDetailController ()<UITableViewDataSource,UITableViewDelegate,QLPreviewControllerDelegate,QLPreviewControllerDataSource>

@property(nonatomic,strong)FSNewSendModel * detailModel;
@property(nonatomic,strong)NSMutableArray * attachmentArray;
@property(nonatomic,strong)NSString * attacmentURL;

@end

@implementation FSNewSendDetailController

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"详情";
    
    self.tableView.hidden = YES;
    
//        UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"阅读记录" style:UIBarButtonItemStylePlain target:self action:@selector(operation)];
//        self.navigationItem.rightBarButtonItem = rightItem;
    
    [self loadData];
    
}

#pragma mark 跳转阅读记录接口
-(void)operation{
    FSNewSendRecordController * readRecordVC = [[FSNewSendRecordController alloc]init];
    readRecordVC.fileId = self.fileId;
    [self.navigationController pushViewController:readRecordVC  animated:YES];
}





#pragma mark 加载网络数据
-(void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId}];
    [HttpTools postWithURL:KexchgeneralURL arrays:array method:KcontentDipatchMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
        self.detailModel = [self getDetailModel:JSON];
        [self.tableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refrshData" object:nil];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}

-(FSNewSendModel*)getDetailModel:(id)json{
    NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
    GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点
    GDataXMLElement *rootElement = [xmlDocument rootElement];
    //获取根节点下的节点
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    FSNewSendModel * model = [[FSNewSendModel alloc]init];
    for (GDataXMLElement *subElement in rootData) {
        NSArray *tempData = [subElement elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempData) {
//           标题
            GDataXMLElement * titleElement = [[data elementsForName:@"GwSubject"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            
            
            GDataXMLElement * themeElement = [[data elementsForName:@"GwTopic"] objectAtIndex:0];
            model.theme = [themeElement stringValue];
            
            GDataXMLElement * sendOrganElement = [[data elementsForName:@"GwCopySendUnit"] objectAtIndex:0];
            model.SendOrgan = [sendOrganElement stringValue];
            
            GDataXMLElement * mainSendOrganElement = [[data elementsForName:@"GwSendUnit"] objectAtIndex:0];
            model.mainSendOrgan = [mainSendOrganElement stringValue];
            
            GDataXMLElement * signDateElement = [[data elementsForName:@"GwPrintDate"] objectAtIndex:0];
            model.signDate = [signDateElement stringValue];
            
            GDataXMLElement * signerElement = [[data elementsForName:@"GwSigner"] objectAtIndex:0];
            model.signer = [signerElement stringValue];
            
            GDataXMLElement * nameElement = [[data elementsForName:@"GwmainUnit"] objectAtIndex:0];
            model.name = [nameElement stringValue];
            
        }
    }
    
    for (GDataXMLElement * element in rootData) {
        NSArray *array = [element elementsForName:@"附件"];
        for (GDataXMLElement * data in array) {
            FSAttachmentModel * attachModel = [[FSAttachmentModel alloc]init];
            GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
            NSString *  name = [nameElement stringValue];
            attachModel.attachmentsTitle = name;
            
            GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
            NSString *  content = [contentElement stringValue];
            attachModel.attachmentsURL = content;
            if (attachModel.attachmentsTitle.length !=0 && attachModel.attachmentsURL.length !=0) {
                [self.attachmentArray addObject:attachModel];
            }
            
        }
    }
    
    return model;
    
}

#pragma mark UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 8;
            break;
        case 1:
            return self.attachmentArray.count;
        default:
            return 1;
            break;
    }
}


#pragma mark UITbableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        FSNewSendDetailCell * cell = [FSNewSendDetailCell cellWihtTableView:tableView];
        cell.detailModel = self.detailModel;
        cell.indexPath = indexPath;
        return cell;
    }else{
        static NSString * cellIdentifier = @"cellId";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        FSAttachmentModel * model = self.attachmentArray[indexPath.row];
        cell.textLabel.text = model.attachmentsTitle;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 44;
    if (indexPath.section ==0) {
        if (indexPath.row ==0) {
            height = [FSHightTool heightbyString:self.detailModel.name font:14 minsWidth:80]+ 35;
            
        }else if (indexPath.row ==1){
            height = [FSHightTool heightbyString:self.detailModel.name font:14 minsWidth:80]+ 35;
            
            
        }else if (indexPath.row ==2){
            
            height = [FSHightTool heightbyString:self.detailModel.signDate font:14 minsWidth:80]+ 35;
            
            
        }else if (indexPath.row ==3){
            
            height = [FSHightTool heightbyString:self.detailModel.signer font:14 minsWidth:80]+ 35;
            
            
        }else if (indexPath.row ==4){
            
            height = [FSHightTool heightbyString:self.detailModel.mainSendOrgan font:14 minsWidth:80]+ 35;
            
            
        }else if (indexPath.row ==5){
            
            height = [FSHightTool heightbyString:self.detailModel.SendOrgan font:14 minsWidth:80]+ 35;
            
            
        }else if (indexPath.row ==6){
            
            height = [FSHightTool heightbyString:self.detailModel.theme font:14 minsWidth:80]+ 35;
            
            
        }else if (indexPath.row ==7){
            
            height = [FSHightTool heightbyString:self.detailModel.title font:14 minsWidth:80]+ 35;
            
        }
    }else if (indexPath.section == 1){
        FSAttachmentModel * model = self.attachmentArray[indexPath.row];
        height = [FSHightTool heightbyString:model.attachmentsTitle font:14 minsWidth:20]+ 35;
    }
    return height;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 21;
    }
    return 0.001;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"附件";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
        if (self.attachmentArray.count) {
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        return bgView;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        FSAttachmentModel * model = self.attachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
    }
    
}

-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
        
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

@end








